package com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.superRepository.SuperRepository;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.repository.entity.HddcB1GeomorlnonfractbltEntity;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.viewobjects.HddcB1GeomorlnonfractbltVO;
import com.css.zfzx.sjcj.modules.hddcB2GeomorphySvyProjectTable.repository.entity.HddcB2GeomorphysvyprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.repository.HddcB3DrillprojecttableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.repository.HddcB3DrillprojecttableRepository;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.repository.entity.HddcB3DrillprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.service.HddcB3DrillprojecttableService;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.viewobjects.HddcB3DrillprojecttableQueryParams;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.viewobjects.HddcB3DrillprojecttableVO;
import com.css.zfzx.sjcj.modules.hddcB4_SampleProjectTable.repository.entity.HddcB4SampleprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB4_SampleResultTable.repository.entity.HddcB4SampleresulttableEntity;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicSvyProjectTable.repository.entity.HddcB7VolcanicsvyprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcDrillHole.repository.entity.HddcDrillholeEntity;
import com.css.zfzx.sjcj.modules.hddcDrillHole.service.HddcDrillholeService;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.repository.entity.HddcMainafsvyregionEntity;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.service.HddcMainafsvyregionService;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.repository.entity.HddcTargetregionEntity;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.service.HddcTargetregionService;
import com.css.zfzx.sjcj.modules.hddcWorkRegion.repository.entity.HddcWorkregionEntity;
import com.css.zfzx.sjcj.modules.hddcWorkRegion.service.HddcWorkregionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author zhangcong
 * @date 2020-11-30
 */
@Service
public class HddcB3DrillprojecttableServiceImpl implements HddcB3DrillprojecttableService {

    @Autowired
    private HddcB3DrillprojecttableRepository hddcB3DrillprojecttableRepository;
    @Autowired
    private HddcB3DrillprojecttableNativeRepository hddcB3DrillprojecttableNativeRepository;
    @Autowired
    private HddcDrillholeService hddcDrillholeService;

    @Override
    public JSONObject queryHddcB3Drillprojecttables(HddcB3DrillprojecttableQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcB3DrillprojecttableEntity> hddcB3DrillprojecttablePage = this.hddcB3DrillprojecttableNativeRepository.queryHddcB3Drillprojecttables(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcB3DrillprojecttablePage);
        return jsonObject;
    }


    @Override
    public HddcB3DrillprojecttableEntity getHddcB3Drillprojecttable(String id) {
        HddcB3DrillprojecttableEntity hddcB3Drillprojecttable = this.hddcB3DrillprojecttableRepository.findById(id).orElse(null);
        return hddcB3Drillprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB3DrillprojecttableEntity saveHddcB3Drillprojecttable(HddcB3DrillprojecttableEntity hddcB3Drillprojecttable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB3Drillprojecttable.setUuid(uuid);
        hddcB3Drillprojecttable.setQualityinspectionStatus("0");
        hddcB3Drillprojecttable.setCreateUser(PlatformSessionUtils.getUserId());
        hddcB3Drillprojecttable.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcB3Drillprojecttable.setIsValid("1");
        this.hddcB3DrillprojecttableRepository.save(hddcB3Drillprojecttable);
        return hddcB3Drillprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB3DrillprojecttableEntity updateHddcB3Drillprojecttable(HddcB3DrillprojecttableEntity hddcB3Drillprojecttable) {
        UpdateUtil.copyNullProperties(hddcB3DrillprojecttableRepository.findByUuidAndIsValid(hddcB3Drillprojecttable.getUuid(), "1"), hddcB3Drillprojecttable);
        hddcB3Drillprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB3Drillprojecttable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB3DrillprojecttableRepository.save(hddcB3Drillprojecttable);
        return hddcB3Drillprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB3Drillprojecttables(List<String> ids) {
        List<HddcB3DrillprojecttableEntity> hddcB3DrillprojecttableList = this.hddcB3DrillprojecttableRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcB3DrillprojecttableList) && hddcB3DrillprojecttableList.size() > 0) {
            for (HddcB3DrillprojecttableEntity hddcB3Drillprojecttable : hddcB3DrillprojecttableList) {
//                this.hddcB3DrillprojecttableRepository.delete(hddcB3Drillprojecttable);
                hddcB3Drillprojecttable.setIsValid("0");
                hddcB3Drillprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB3Drillprojecttable.setUpdateTime(new Date());
                this.hddcB3DrillprojecttableRepository.save(hddcB3Drillprojecttable);
            }
        }
    }

    @Override
    public HddcB3DrillprojecttableEntity findById(String id) {
        HddcB3DrillprojecttableEntity hddcB3DrillprojecttableEntity = hddcB3DrillprojecttableRepository.findbyId(id);
        return hddcB3DrillprojecttableEntity;
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcB3DrillprojecttableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB3DrillprojecttableEntity> yhDisasterEntities = hddcB3DrillprojecttableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB3DrillprojecttableVO> list = new ArrayList<>();
        for (HddcB3DrillprojecttableEntity entity : yhDisasterEntities) {
            HddcB3DrillprojecttableVO yhDisasterVO = new HddcB3DrillprojecttableVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "钻探工程表", "钻探工程表", HddcB3DrillprojecttableVO.class, "钻探工程表.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcB3DrillprojecttableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB3DrillprojecttableVO.class, params);
            List<HddcB3DrillprojecttableVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size()));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcB3DrillprojecttableVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcB3DrillprojecttableVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    @Autowired
    SuperRepository superRepository;

    @Transactional
    @Override
    public int dataQualityCheck() {
        List<HddcB3DrillprojecttableEntity> updateList = new ArrayList<>();
        List<HddcB3DrillprojecttableEntity> listAll = hddcB3DrillprojecttableRepository.findByAll();
        for (HddcB3DrillprojecttableEntity b2All : listAll) {
            String str = "";
            if (StringUtils.isEmpty(b2All.getId())) {
                str += "【钻探工程表】工程编号为空。";
            } else {
                List<HddcDrillholeEntity> hddcDrillholeEntities = hddcDrillholeService.findByProjectId(b2All.getId());
                if (hddcDrillholeEntities.size() <= 0 || hddcDrillholeEntities == null) {
                    str += "【钻探工程表】表单中的工程编号与【钻孔】中的工程编号不一致。";
                } else {
                    int collectedsamplecount=0;
                    for (HddcDrillholeEntity hddcDrillholeEntity: hddcDrillholeEntities){
                        collectedsamplecount=collectedsamplecount+hddcDrillholeEntity.getCollectedsamplecount();
                    }
                    if (b2All.getCollectedsamplecount() == null) {
                        str += "【钻探工程表】采集样品总数为空。";
                    } else {
                        if (b2All.getCollectedsamplecount() != collectedsamplecount) {
                            str += "【钻探工程表】表单中的采集样品总数与【钻孔】中的采集样品总数不一致。";
                        }
                    }

                }
            }
            if (str.isEmpty()) {
                str += "【采样工程表】与【样品测试结果表】质检成功";
                b2All.setQualityinspectionStatus("1");
            } else {
                b2All.setQualityinspectionStatus("2");
            }
            b2All.setQualityinspectionComments(null);
            String[] split = str.split("。");
            for (int i = 0; i < split.length; i++) {
                if (i == 0) {
                    b2All.setExtends1(split[i]);
                    b2All.setExtends2(null);
                    b2All.setExtends3(null);
                } else if (i == 1) {
                    b2All.setExtends2(split[i]);
                    b2All.setExtends3(null);
                } else if (i == 2) {
                    b2All.setExtends3(split[i]);
                }
            }
            updateList.add(b2All);
        }
        superRepository.batchUpdate(updateList);
        return 1;
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcB3DrillprojecttableVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcB3DrillprojecttableEntity yhDisasterEntity = new HddcB3DrillprojecttableEntity();
            HddcB3DrillprojecttableVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcB3Drillprojecttable(yhDisasterEntity);
        }
    }

}
